/*
 * @Description:
 * @Version: 1.0
 * @Autor: ycb
 * @Date: 2022-03-16 09:07:58
 * @LastEditors: ycb
 * @LastEditTime: 2022-03-16 13:50:31
 */
package rabiitmq

import (
	"log"

	"github.com/streadway/amqp"
)

type RabbitMQWorkClient struct {
	// 用户
	User string
	// 密码
	Pwd string
	// ip
	IP string
	// port
	Port string
	// channel
	channel *amqp.Channel
}

func (client *RabbitMQWorkClient) Connect() bool {
	url := "amqp://" + client.User + ":" + client.Pwd + "@" + client.IP + ":" + client.Port + "/"
	// 新建一个连接
	connect, err := amqp.Dial(url)
	if err != nil {
		log.Fatalf("%s: %s", "Failed to connect to RabbitMQ", err)
		connect.Close()
		return false
	}

	// 打开一个channel
	ch, err := connect.Channel()
	if err != nil {
		log.Fatalf("%s: %s", "Failed to open a channel", err)
		ch.Close()
		return false
	}

	client.channel = ch
	return true
}

func (client *RabbitMQWorkClient) SendMsg(queue_name string, bytes []byte) bool {
	// 声明或者创建一个队列用来保存消息
	q, err := client.channel.QueueDeclare(
		// 队列名称
		queue_name, // name
		false,      // durable
		false,      // delete when unused
		false,      // exclusive
		false,      // no-wait
		nil,        // arguments
	)

	if err != nil {
		log.Fatalf("%s: %s", "Failed to declare a queue", err)
		return false
	}

	err = client.channel.Publish(
		"",     // exchange
		q.Name, // routing key
		false,  // mandatory
		false,  // immediate
		amqp.Publishing{
			ContentType: "text/plain",
			Body:        bytes,
		})

	if err != nil {
		log.Fatalf("%s: %s", "Failed to publish a message", err)
		return false
	}

	return true

}

func (client *RabbitMQWorkClient) RecvMsg(queue_name string) bool {
	// 声明或者创建一个队列用来保存消息
	q, err := client.channel.QueueDeclare(
		// 队列名称
		queue_name, // name
		false,      // durable
		false,      // delete when unused
		false,      // exclusive
		false,      // no-wait
		nil,        // arguments
	)

	if err != nil {
		log.Fatalf("%s: %s", "Failed to declare a queue", err)
		return false
	}

	// 定义一个消费者
	msgs, err := client.channel.Consume(
		q.Name, // queue
		"",     // consumer
		true,   // auto-ack
		false,  // exclusive
		false,  // no-local
		false,  // no-wait
		nil,    // args
	)

	if err != nil {
		log.Fatalf("%s: %s", "Failed to register a consume", err)
		return false
	}

	go func() {
		for d := range msgs {
			log.Printf("Received a message: %s", d.Body)
		}
	}()

	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	select {}

}
